<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>摄像头</title>
</head>
<body>
<button onclick="startCamera()">开启摄像头</button>
<hr>
<div id="box">
    <button id="btn" style="display:none">自拍</button>
    <br>
</div>

<br>

<div id="cam_box"></div>

<script>
    //兼容处理
    navigator.getUserMedia || (navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia);

    function startCamera(){
        navigator.getUserMedia(
            {
                video:true,
                audio:true
            },
            function(stream){
                //创建video元素
                var video = document.createElement("video");
                video.id = "myvideo";
                //指定src
                if (window.URL) {
                    console.log(window.URL)
                    video.src = window.URL.createObjectURL(stream);
                } else {
                    video.src = stream;
                }
                //添加video到页面
                document.querySelector("#box").appendChild(video);
                btn.style.display = "block";

                //视频播放
                video.play();
            },
            function(error){
                console.log(error);
            }
        )
    }
    var btn = document.querySelector("#btn");
    btn.onclick = function(){
        var canvas = document.createElement("canvas");
        canvas.width = 640;
        canvas.height = 480;
        var cxt = canvas.getContext("2d");
        cxt.drawImage(document.querySelector("#myvideo"), 0, 0, 640, 480);
        document.querySelector("#cam_box").appendChild(canvas);
    }
</script>
</body>
</html>
